import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from './auth'
import store from '@/store'
import router from '@/router'
// console.log(router)
// import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = getToken()
    if (token) config.headers['x-token'] = token

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  async response => {
    const { data, errmsg, errno } = response.data
    if (errno === 0) {
      return data
    } else {
      if (errno === 9997) {
        await store.dispatch('user/logoutAction')
        // 跳转到登录页面 携带当前页面的路由地址
        const url = router.history?.current?.path
        console.log(url)
        router.push(`/login?redirect=${url}`)
      }
      Message.error(errmsg)
      return Promise.reject(errmsg)
    }
  },
  error => {
    console.log('err' + error) // for debug

    return Promise.reject(error)
  }
)

export default service
